import socket
import pygame
import sys
import json

config = json.loads(open('./config.json').read())

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.connect((config['server']['ip'],int(config['server']['port'])))

def get_json(sub_sk):
    t = ''
    while t == '':
        t = str(sub_sk.recv(3),encoding='utf-8')
    len = int(t,16)
    rec = ''
    while len > 0:
        if len > 1450:
            rec += str(sub_sk.recv(1450),encoding='utf-8')
            len-=1450
        else:
            rec += str(sub_sk.recv(len),encoding='utf-8')
            len = 0
    rec = json.loads(rec)
    return rec

def send_json(jsons):
    global sk
    jsons_str = json.dumps(jsons)
    sk.send(bytes("%03x"%len(bytes(jsons_str,encoding='utf-8')),encoding='utf-8'))
    sk.send(bytes(jsons_str,encoding='utf-8'))

def drawapi(x,y,r,g,b):
    global screen,config
    pointsize = config['canvas']['pointsize']
    for i in range(pointsize*x,pointsize*(x+1)):
        for j in range(pointsize*y,pointsize*(y+1)):
            screen.set_at([i,j],[r,g,b])

# -1 是背景
# -2 场景外部
# -3 是吃的
# 其他是场景颜色
def draw(boardd):
    for i in range(len(boardd)):
        for j in range(len(boardd[0])):
            if boardd[i][j] == -2:
                drawapi(i,j,
                    config['colors']['out'][0],config['colors']['out'][1],config['colors']['out'][2])
            elif boardd[i][j] == -1:
                drawapi(i,j,
                    config['colors']['background'][0],config['colors']['background'][1],config['colors']['background'][2])
            elif boardd[i][j] == -3:
                drawapi(i,j,
                    config['colors']['food'][0],config['colors']['food'][1],config['colors']['food'][2])
            else:
                drawapi(i,j,\
                    (boardd[i][j]+1)*137%255,(boardd[i][j]+1)*73%255,(boardd[i][j]+1)*92%255)
    pygame.display.flip()

pygame.init()
screen=pygame.display.set_caption('game')
res = get_json(sk)['see']
screen=pygame.display.set_mode([config['canvas']['pointsize']*(res['l']+res['r']),config['canvas']['pointsize']*(res['u']+res['d'])])

drawapi(0,0,0,255,0)
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                send_json({'t':'u'})
                # print('u')
            if event.key == pygame.K_DOWN:
                send_json({'t':'d'})
                # print('d')
            if event.key == pygame.K_LEFT:
                send_json({'t':'l'})
                # print('l')
            if event.key == pygame.K_RIGHT:
                send_json({'t':'r'})
                # print('r')
        if event.type==pygame.QUIT:
            sys.exit()
    send_json({'t':'g'})
    try:
        board = get_json(sk)['res']
    except KeyError:
        sys.exit()
    draw(board)